package org.zjt.agent;

import org.zjt.agent.convertor.ClassConverter;
import org.zjt.agent.generate.ByteCodeGenerator;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Optional;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-07-04 下午12:03
 * @see
 */
public class MyClassFileTransformer implements ClassFileTransformer {

    private static final byte[] EMPTY_BYTES = {};


    private final ClassConverter classConverter;

    public MyClassFileTransformer(ClassConverter classConverter) {
        this.classConverter = classConverter;
    }


    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        className = className.replace("/",".");
        ClassDefineDescription classDefineDescription = ClassDefineDescription.builder().classLoader(loader).className(className).classFileBuffer(classfileBuffer).build();
        Optional<byte[]> generateCodeByte = classConverter.convert(classDefineDescription);
        return generateCodeByte.isPresent() ? generateCodeByte.get() : EMPTY_BYTES;
    }
}
